package config

import (
	"fmt"
	"github.com/spf13/viper"
	"strings"
)

type Config struct {
	v *viper.Viper
}

var C *Config

//从指定的目录中匹配一个
func New(filename string, path ...string) *Config {
	if filename == "" && !strings.Contains(filename, "."){
		filename = "config.yaml"
	}
	if len(path) == 0 {
		path = append(path, "./")
	}

	fileinfo := strings.Split(filename, ".")

	v := viper.New()
	v.SetConfigName(fileinfo[0]) // name of config file (without extension)
	v.SetConfigType(fileinfo[1]) // REQUIRED if the config file does not have the extension in the name
	for _, s := range path {
		v.AddConfigPath(s)
	}

	err := v.ReadInConfig()
	if err != nil {
		panic(fmt.Errorf("Fatal error config file: %w \n", err))
	}

	v.WatchConfig()
	c := &Config{v: v}
	C = c
	return c
}

func (c *Config) GetString(key string) string {
	return c.v.GetString(key)
}

func (c *Config) GetStringSlice(key string) []string {
	return c.v.GetStringSlice(key)
}

func (c *Config) GetInt(key string) int {
	return c.v.GetInt(key)
}

func (c *Config) GetInt64(key string) int64 {
	return c.v.GetInt64(key)
}

func (c *Config) GetFloat64(key string) float64 {
	return c.v.GetFloat64(key)
}

func (c *Config) Get(key string) interface{} {
	return c.v.Get(key)
}
